import { getAllAssort, getAllCoin } from "@/api/assort"
import { ref, watch, onUnmounted, onMounted } from "vue";
import { useUserInfo } from "@/stores/userInfo.ts";
const { userInfo } = useUserInfo();
export function useStartSpotWebsocket() {
  const member = userInfo;
  const socketData = ref([]);
  const pingTimer = ref();
  const spotSocket = ref();
  const userIdOrDate = ref();
  const spotWs = ref();
  const coinTypeId = ref();
  const coinTypeList = ref([]);
  const getAllAssort1 = (type) => {
    getAllAssort(type).then((res) => {
      coinTypeList.value = res.data;

      if (member) {
        userIdOrDate.value = member.userId;
        coinTypeId.value = res.data[1].id;
      } else {
        userIdOrDate.value = Date.now();
        coinTypeId.value = res.data[1].id;
      }
      spotWs.value = `${import.meta.env.VITE_SPOT_WEBSOCKET}${userIdOrDate.value
        }/BTC-USDT/5MIN/${coinTypeId.value.toString()}`;

      getAllCoin1();
      startSpotWebsocket();
    });
  };
  const startSpotWebsocket = () => {
    if (spotSocket.value) {
      WebsocketOnclose();
    }
    spotSocket.value = new WebSocket(spotWs.value);
    spotSocket.value.binaryType = "arraybuffer";
    spotSocket.value.onopen = WebsocketOnopen;
    spotSocket.value.onmessage = WebsocketOnmessage;
    spotSocket.value.onClose = WebsocketOnclose;
    spotSocket.value.onerror = WebsocketOnerror;
  };

  const WebsocketOnopen = () => {
    Toime();
    pingTimer.value = setInterval(() => {
      Toime();
    }, 30000);
  };
  const Toime = () => {
    let arr = JSON.stringify({
      ping: "ping",
      symbol: "BTC-USDT",
      time: "5MIN",
      assortId: coinTypeId.value,
    });
    spotSocket.value.send(arr);
  };
  const WebsocketOnmessage = (e) => {
    const arrayBuffer = e.data;
    const decoder = new TextDecoder("utf-8");
    const jsonString = decoder.decode(arrayBuffer);
    if (jsonString != "pong") {
      const data = JSON.parse(jsonString);
      if (data.arg == "assort") {
        socketData.value = data.data;

      }
    }
  };
  const WebsocketOnclose = function () {
    clearInterval(pingTimer.value);
    spotSocket.value.close();
  };
  const WebsocketOnerror = function (err) {
    // window.location.reload();
  };
  const getAllCoin1 = () => {
    getAllCoin(coinTypeId.value, userIdOrDate.value)
      .then((res) => {
        socketData.value = res.data || [];
      });
  };

  onMounted(() => { });
  onUnmounted(() => {
    if (spotSocket.value) {
      WebsocketOnclose();
    }
  });
  return {
    coinTypeList,
    getAllAssort1,
    getAllCoin1,
    socketData,
    coinTypeId,
    Toime,
  };
}
